<template>
    <div class="purchase-apply-container">
        <!-- Loading 覆盖层 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-content">
                <el-icon class="is-loading" color="#409EFF" :size="32">
                    <Loading />
                </el-icon>
                <div class="loading-text">正在初始化单位数据...</div>
            </div>
        </div>


        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span class="form-title">采购订单</span>
                    <div class="header-actions">
                        <el-button>商品记录</el-button>
                        <el-button type="primary" @click="handleSubmit" :disabled="!selectedSupplier.SupplierName">{{
                            isEdit ? '保存修改' : '保存并新增' }}</el-button>
                        <el-button type="primary" @click="handleSubmit2"
                            :disabled="!selectedSupplier.SupplierName">保存</el-button>
                        <el-button>批量导入</el-button>
                        <el-button @click="audit">审核</el-button>
                        <el-button @click="chooseOrder">选择订单</el-button>
                    </div>
                </div>
            </template>
            <div class="form-content">
                <el-form :model="form" label-width="100px" class="fixed-height-dialog" width="60%">
                    <!-- 供应商信息头部 -->
                    <div class="supplier-header">
                        <div class="supplier-info-row">
                            <div class="info-item">
                                <span class="label">供应商:</span>
                                <el-input v-model="selectedSupplier.SupplierName" placeholder="选择供应商(必选)" clearable
                                    disabled style="width: 200px; margin-right: 20px;">
                                    <template #append>
                                        <el-button :icon="Search" @click="supplierDialog.open()" />
                                    </template>
                                </el-input>
                                <span class="label">业务员:</span>
                                <el-input v-model="form.created_by" placeholder="业务员" clearable style="width: 120px;" disabled>
                                </el-input>
                                <!-- <el-input v-model="form.buyer" placeholder="业务员" clearable disabled
                                    style="width: 120px;" /> -->
                            </div>
                            <div class="info-item">
                                <span class="label">单据日期:</span>
                                <el-date-picker v-model="form.procurementOrder_date" type="date" placeholder="选择单据日期"
                                    style="width: 140px;" />
                                <span class="label" style="margin-left: 20px;">交货日期:</span>
                                <el-date-picker v-model="form.delivery_date" type="date" placeholder="选择交货日期"
                                    style="width: 140px;" />
                            </div>
                        </div>
                        <div class="supplier-detail-row">
                            <div class="info-item">
                                <span class="label">供应商发货地址:</span>
                                <el-input v-model="form.supplier_shippingAddress" placeholder="供应商发货地址" clearable
                                    style="width: 300px;" />
                            </div>
                        </div>
                    </div>

                    <!-- 采购物品明细 -->
                    <div class="form-section">
                        <div class="section-header">
                            <div class="section-title">
                                采购订单明细
                                <el-button type="primary" link @click="openGoodsDialog" style="margin-left: 10px;">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>添加物品
                                </el-button>
                                <span class="item-count" v-if="form.detailList.length > 0">
                                    共 {{ form.detailList.length }} 个物品
                                </span>
                            </div>
                        </div>

                        <el-table :data="form.detailList" border style="width: 100%" class="items-table"
                            empty-text="暂无物品，请点击添加物品" :summary-method="getSummary" show-summary>
                            <el-table-column label="序号" type="index" width="60" align="center" />
                            <el-table-column label="商品编号" prop="goods_code" width="120" align="center" />
                            <el-table-column label="物品名称" prop="goods_name" min-width="150" align="center" />
                            <el-table-column label="规格型号" prop="goods_specifiction  " min-width="120" align="center" />
                            <el-table-column label="品牌" prop="goods_brand" width="100" align="center" />
                            <el-table-column label="单位" prop="goods_moreUint" width="120" align="center">
                                <template #default="scope">
                                    <el-select v-model="scope.row.goods_moreUint" style="width: 95%"
                                        :disabled="!scope.row.goods_moreUint" @change="calculateDetailPrice(scope.row)">
                                        <template v-if="scope.row.unitList">
                                            <el-option v-for="item in scope.row.unitList" :key="item.id"
                                                :label="item.name" :value="item.name" />
                                        </template>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="仓库" prop="goods_store" width="180" align="center">
                                <template #default="{ row, $index }">
                                    <el-input :value="row.goods_store" readonly placeholder="选择仓库"
                                        @click="openWarehouseDialog(row, $index)" style="width: 140px" />
                                </template>
                            </el-table-column>
                            <el-table-column label="可用库存" prop="store_userNum" width="100" align="center" />
                            <el-table-column label="数量" prop="procureDetails_num" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.procureDetails_num" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" :min="1" :max="99999" :controls="false"
                                        placeholder="数量" />
                                </template>
                            </el-table-column>
                            <el-table-column label="基本单位" prop="goods_unit" width="120" align="center" />
                            <el-table-column label="基本数量" prop="unit_num" width="120" align="center"
                                @change="calculateDetailPrice(row)" />
                            <el-table-column label="交货日期" width="160" align="center">
                                <template #default="{ row }">
                                    <el-date-picker v-model="row.procurementDetails_Deliverydate" style="width: 120px;"
                                        type="date" size="small"></el-date-picker>
                                </template>
                            </el-table-column>
                            <el-table-column label="购货单价" prop="goods_price" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.goods_price" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" :precision="2" :controls="false" :min="0"
                                        placeholder="0.00" />
                                </template>
                            </el-table-column>
                            <el-table-column label="赠品" prop="gift" width="80" align="center">
                                <template #default="{ row }">
                                    <el-checkbox v-model="row.gift" label="赠品" :true-label="true" :false-label="false"
                                        @change="calculateDetailPrice(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="含税单价" prop="afterDiscount_price" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.afterDiscount_price" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" disabled
                                        oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="折后含税单价" prop="afterDiscount_taxPrice" width="160" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.afterDiscount_taxPrice" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" disabled
                                        oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="折扣率(%)" prop="discount" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.discount" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)"
                                        oninput="value=value.replace(/[^\d]/g,'')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="折扣额" prop="discount_amount" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.discount_amount" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" disabled
                                        oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="折后单价" prop="discount_price" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.discount_price" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" disabled
                                        oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" prop="amount" width="80" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.amount" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)"
                                        oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')"
                                        disabled />
                                </template>
                            </el-table-column>
                            <el-table-column label="税率(%)" prop="tax" width="120" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.tax" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)"
                                        oninput="value=value.replace(/[^\d]/g,'')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="税额" prop="tax_amount" width="80" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.tax_amount" style="width: 80px" size="small"
                                        @change="calculateDetailPrice(row)" disabled
                                        oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                                </template>
                            </el-table-column>
                            <el-table-column label="价税合计" prop="totalAmount_includingTax" width="120" align="center">
                                <template #default="{ row }">
                                    ¥{{ row.totalAmount_includingTax?.toFixed(2) || '0.00' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" align="center" fixed="right">
                                <template #default="{ $index }">
                                    <el-button type="danger" link @click="removeItem($index)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <!-- 其他信息 -->
                    <div class="supplier-detail-row" style="margin-bottom: 20px;">
                        <el-input v-model="form.procurementOrder_remark" placeholder="暂无备注信息" type="textarea" />
                    </div>
                    <div class="supplier-detail-row" style="margin-bottom: 12px;">
                        <span class="label">金额:</span>
                        <el-input v-model="form.procurement_amount" clearable style="width: 100px; " disabled />
                        <span class="label">交货方式:</span>
                        <el-select v-model="form.delivery_method" placeholder="" clearable style="width: 120px;">
                            <el-option value="快递物流">快递物流</el-option>
                            <el-option value="自配送">自配送</el-option>
                            <el-option value="自提">自提</el-option>
                            <el-option value="其他">其他</el-option>
                        </el-select>
                    </div>
                </el-form>
            </div>
        </el-card>

        <!-- 商品搜索列表弹出对话框 -->
        <!-- <el-dialog v-model="openGoodsDialogView" title="商品搜索列表" width="40%" style="height: auto; width: 800px;"
            draggable :show-close="true" :destroy-on-close="false"> -->
        <!-- 调用商品的搜索组件 -->
        <!-- <FreeGoodsSelect v-model="openGoodsDialogView" @update:visible="openGoodsDialogView = $event"
                @confirm="handleGoodsConfirm" ref="freeGoodsRef">
            </FreeGoodsSelect>
            <br /><br />
        </el-dialog> -->

        <el-dialog v-model="openGoodsDialogView" title="商品搜索列表" width="40%" style="height: auto; width: 800px;"
            draggable :show-close="true" :destroy-on-close="false" :class="{ 'hidden-dialog': isInitializing }">
            <!-- 调用商品的搜索组件 -->
            <FreeGoodsSelect v-model="openGoodsDialogView" @update:visible="openGoodsDialogView = $event"
                @confirm="handleGoodsConfirm" ref="freeGoodsRef">
            </FreeGoodsSelect>
            <br /><br />
        </el-dialog>

        <!-- 供应商对话框 -->
        <SupplierDialog ref="supplierDialog" :supplier-list="SupplierList" @confirm="handleSupplierConfirm" />
    </div>


    <!-- 源单选择对话框 -->
    <el-dialog v-model="openComparisonGoodsDialogView" title="选择商品" width="70%">
        <div class="supplier-dialog-content">
            <div class="search-area">
                <el-input v-model="goodsSearch" placeholder="搜索商品名称或编号" style="width: 300px;" clearable>
                    <template #append>
                        <el-button @click="searchGoods">
                            <el-icon>
                                <Search />
                            </el-icon>
                        </el-button>
                    </template>
                </el-input>
            </div>

            <el-table :data="comparisonGoodsList" border style="width: 100%;height: 350px;" class="supplier-table"
                v-loading="comparisonGoodsLoading" @selection-change="handleComparisonSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column label="商品编号" prop="goods_code" width="120" />
                <el-table-column label="商品名称" prop="goods_name" min-width="150" />
                <el-table-column label="规格型号" prop="goods_specifiction" width="120" />
                <el-table-column label="品牌" prop="goods_brand" width="100" />
                <el-table-column label="单位" prop="goods_unit" width="80" />
                <el-table-column label="报价单价" prop="supply_price" width="100" align="right">
                    <template #default="{ row }">
                        <span>¥{{ row.supply_price }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="报价税率" prop="supply_tax" width="100" align="right">
                    <template #default="{ row }">
                        <span>{{ row.supply_tax }}%</span>
                    </template>
                </el-table-column>
                <el-table-column label="供应商" prop="supplier_name" width="150" />
            </el-table>

            <el-pagination style="float: left; margin-top: 16px;" background layout="prev, pager, next, jumper"
                :total="comparisonGoodsPageInfo.total" :page-size="comparisonGoodsPageInfo.pageSize"
                :current-page="comparisonGoodsPageInfo.pageNum" @current-change="changePage" />
            <div class="dialog-footer" style="text-align: right; margin-top: 20px;">
                <el-button @click="openComparisonGoodsDialogView = false">取消</el-button>
                <el-button type="primary" @click="confirmComparisonGoods"
                    :disabled="selectedComparisonGoods.length === 0">
                    确定选择
                </el-button>
            </div>
        </div>
    </el-dialog>

    <!-- 仓库搜索列表弹出对话框 -->
    <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable :show-close="true">
        <!-- 调用仓库的搜索组件 -->
        <WareHouse ref="warehouseRef"
            :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
        <br /><br />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="warehouseVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmWarehouseSelection">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import WareHouse from '@/views/basic/WareHouse.vue'
import SupplierDialog from '@/util/SupplierDialog.vue'
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';

let freeGoodsRef = ref();

// import { it } from 'element-plus/es/locale';
// import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
// 判断是否为编辑模式
const isEdit = computed(() => route.query.isEdit === 'true')

const updateUnitNum = (row) => {
    if (!row.goods_moreUint || !Array.isArray(row.unitList) || row.unitList.length === 0) {
        row.unit_num = '';
        return;
    }

    // 找到当前选中的单位
    const selectedUnit = row.unitList.find(unit => unit.name === row.goods_moreUint);

    if (!selectedUnit) {
        row.unit_num = '';
        return;
    }

    // 获取采购数量（用户输入）
    const procureNum = parseFloat(row.procureDetails_num) || 0;

    // 计算基本数量 = 采购数量 × 单位换算系数（conversion）
    const baseNum = procureNum * (parseFloat(selectedUnit.conversion) || 1);

    // 保留合理小数位（比如最多3位，或根据业务决定）
    row.unit_num = isNaN(baseNum) ? '' : baseNum;
};

// onMounted(() => {
//     // 临时打开 Dialog，让子组件挂载
//     openGoodsDialogView.value = true;
//     nextTick(() => {
//         openGoodsDialogView.value = false; // 立即关闭
//         console.log('子组件实例:', freeGoodsRef.value.unitOptionsMap); // 现在应该有值了（因为 destroy-on-close=false）

//         if (isEdit.value) {
//             loadEditData();
//         }
//     });

//     // if (isEdit.value) {
//     //     loadEditData()
//     // }
// })


// 添加初始化状态
const loading = ref(false)
const isInitializing = ref(false)

onMounted(async () => {
    loading.value = true;
    isInitializing.value = true;

    try {
        console.log('开始静默加载单位数据...');

        // 静默打开 Dialog（但通过CSS隐藏）
        openGoodsDialogView.value = true;

        // 等待单位数据加载
        let retryCount = 0;
        const maxRetries = 50; // 5秒

        await new Promise((resolve) => {
            const checkInterval = setInterval(() => {
                retryCount++;

                if (freeGoodsRef.value?.unitOptionsMap &&
                    Object.keys(freeGoodsRef.value.unitOptionsMap).length > 0) {
                    clearInterval(checkInterval);
                    console.log(`单位数据加载成功，耗时: ${retryCount * 100}ms`);
                    resolve();
                } else if (retryCount >= maxRetries) {
                    clearInterval(checkInterval);
                    console.warn('单位数据加载超时');
                    resolve();
                }
            }, 100);
        });

    } catch (error) {
        console.error('加载单位数据失败:', error);
    } finally {
        // 先关闭对话框
        openGoodsDialogView.value = false;

        // 等待对话框关闭动画完成
        await new Promise(resolve => setTimeout(resolve, 300));

        // 然后移除初始化状态
        isInitializing.value = false;
        loading.value = false;

        console.log('单位数据加载完成');
    }

    // 加载编辑数据
    if (isEdit.value) {
        await loadEditData();
    }
});


const warehouseVisible = ref(false)
const warehouseRef = ref()
const currentEditingRow = ref(null)  // 当前正在编辑的行数据
const currentEditingIndex = ref(-1)  // 当前正在编辑的行索引


// 打开仓库选择对话框
const openWarehouseDialog = (row, index) => {
    currentEditingRow.value = row
    currentEditingIndex.value = index
    warehouseVisible.value = true

    // 如果有需要，可以在这里设置初始选中的仓库
    // 根据你的 WareHouse 组件的 API 来设置
}

// 确认仓库选择
const confirmWarehouseSelection = async () => {
    if (warehouseRef.value && warehouseRef.value.selectedArray && warehouseRef.value.selectedArray.length > 0) {
        // 获取选中的仓库（假设单选，取第一个）
        const selectedWarehouse = warehouseRef.value.selectedArray[0]

        // 更新当前行的仓库信息
        if (currentEditingRow.value) {
            currentEditingRow.value.goods_store = selectedWarehouse.name
            // 如果需要存储仓库编码
            currentEditingRow.value.warehouse_code = selectedWarehouse.code
            // 或者其他需要的字段
            // currentEditingRow.value.warehouse_id = selectedWarehouse.id

            //处理当前仓库的可用库存

            const params = {
                warehouse_name: currentEditingRow.value.goods_store,
                goods_id: currentEditingRow.value.goods_id
            }
            const res = await axios.get("/lxw/getStoreUseNum", { params })
            if (res.data.code == 5200) {
                const inventory = res.data.Inventory
                console.log("仓库对象",inventory)
                if (inventory?.totalNumber == null) {
                    currentEditingRow.value.store_userNum = 0
                } else {
                    currentEditingRow.value.store_userNum = inventory.totalNumber - inventory.lockedNumber
                }

            }
        }


        // 清空选择
        if (warehouseRef.value.clearSelected) {
            warehouseRef.value.clearSelected()
        }
    }



    // 关闭对话框
    warehouseVisible.value = false
    resetEditingState()
}

// 重置编辑状态
const resetEditingState = () => {
    currentEditingRow.value = null
    currentEditingIndex.value = -1
}

// 加载编辑数据
const loadEditData = async () => {
    try {
        // 从本地存储获取数据
        const procurementOrder_id = route.query.procurementOrder_id;
        if (!procurementOrder_id) return;

        const res = await axios.get(`/lxw/selectByOrderId?procurementOrder_id=${procurementOrder_id}`);
        console.log("修改数据回显", res)
        if (res.data.code == 5200) {
            const data = res.data.procurementOrder;
            console.log()
            // 填充主表单数据
            Object.assign(form, {
                procurementOrder_id: data.procurementOrder_id,
                procurementOrder_code: data.procurementOrder_code,
                procurement_code: data.procurement_code,
                salesSlip_code: data.salesSlip_code,
                comparison_code: data.comparison_code,
                procurement_amount: data.procurement_amount,
                discount_amount: data.discount_amount,
                afterDiscount_amount: data.afterDiscount_amount,
                tax_amount: data.tax_amount,
                procurementOrder_num: data.procurementOrder_num,
                procurementOrder_status: data.procurementOrder_status,
                created_by: data.created_by,
                created_id: data.created_id,
                delivery_method: data.delivery_method,
                companyCode: data.companyCode,
                procurementOrder_date: data.procurementOrder_date,
                delivery_date: data.delivery_date,
                supplier_code: data.supplier_code,
                supplier_name: data.supplier_name,
                procurementOrder_remark: data.procurementOrder_remark,
                isDelete: data.isDelete,
                detailList: data.detailList || []
            })
            let map = freeGoodsRef.value.unitOptionsMap; //获取到的所有商品的单位列表
            form.detailList.forEach(i => { //
                console.log("detailList[i]: ", i);
                i.unitList = map[i.goods_id];
                console.log("i.unitList: ", i.unitList);
            })


            // 填充供应商信息
            Object.assign(selectedSupplier, {
                SupplierName: data.supplier_name,
                SupplierCode: data.supplier_code,
                supplierAddress: data.supplier_shippingAddress || ''
            })


            ElMessage.success('已加载编辑数据')
        }
    } catch (error) {
        console.error('加载编辑数据失败:', error)
        ElMessage.error('加载数据失败')
    }
}

// 对话框引用
const supplierDialog = ref(null);
// 选择的供应商
const selectedSupplier = reactive({
    SupplierName: '',
    SupplierConcat: '',
    SupplierPhone: '',
    supplierAddress: '',
    totalDebt: 0
});
// 表单数据
const form = reactive({
    procurementOrder_id: '',
    procurementOrder_code: '',
    procurement_code: '',
    salesSlip_code: '',
    comparison_code: '',
    procurement_amount: '',
    discount_amount: '',
    afterDiscount_amount: '',
    tax_amount: '',
    procurementOrder_num: '',
    procurementOrder_status: 1,
    created_by: sessionStorage.getItem("name"),
    created_id:'',
    delivery_method: '',
    companyCode: 'CNY001',
    procurementOrder_date: new Date(),
    delivery_date: '',
    supplier_code: '',
    supplier_name: '',
    procurementOrder_remark: '',
    isDelete: 0,
    supplier_shippingAddress: selectedSupplier.supplierAddress || '',
    detailList: []
})

// 文件上传
const fileList = ref([])

const calculateDetailPrice = (row) => {
    updateUnitNum(row)
    console.log("是否是赠品", row.gift)
    if (row.gift) {
        row.afterDiscount_price = 0
        row.taxPrice = 0
        row.afterDiscount_taxPrice = 0
        row.discount = 0
        row.discount_price = 0
        row.discount_amount = 0
        row.amount = 0
        row.tax = 0
        row.tax_amount = 0
        row.totalAmount_includingTax = 0
    } else {
        console.log(row.goods_price)
        console.log(row.procureDetails_num)
        if (row.goods_price == 0 || row.procureDetails_num == 0) {
            row.afterDiscount_price = 0
            row.taxPrice = 0
            row.afterDiscount_taxPrice = 0
            row.discount = 0
            row.discount_price = 0
            row.discount_amount = 0
            row.amount = 0
            row.tax = 0
            row.tax_amount = 0
            row.totalAmount_includingTax = 0
        } else {
            row.discount_price = formatPrice(row.goods_price * (1 - (row.discount || 0) / 100))
            row.discount_amount = formatPrice((row.goods_price - row.discount_price) * row.unit_num)

            row.afterDiscount_taxPrice = formatPrice(row.discount_price * (1 + (row.tax || 0) / 100))
            row.totalAmount_includingTax = formatPrice(row.afterDiscount_taxPrice * row.unit_num)

            row.afterDiscount_price = formatPrice(row.goods_price * (1 + (row.tax || 0) / 100))
            row.tax_amount = formatPrice((row.afterDiscount_taxPrice - row.discount_price) * row.unit_num)

            row.amount = formatPrice(row.discount_price * row.unit_num)


        }
    }

    calculateTotalAmount()
    calculateTotalDiscountAmount()
    calculateTotal()
    calculateTotalTax()
    calculateTotalNum()
}
const formatPrice = (num) => Math.round(num * 100) / 100
// 计算折扣后金额（实付金额）
const calculateTotalAmount = () => {
    const total = form.detailList.reduce((sum, item) => {
        return sum + (parseFloat(item.totalAmount_includingTax) || 0);
    }, 0);
    form.procurement_amount = total.toFixed(2);
};
//计算总折扣额
const calculateTotalDiscountAmount = () => {
    const total = form.detailList.reduce((sum, item) => {
        return sum + (parseFloat(item.discount_amount) || 0);
    }, 0);
    form.discount_amount = total.toFixed(2);
}
//计算折扣前金额（金额）
const calculateTotal = () => {
    const total1 = form.detailList.reduce((sum, item) => {
        return sum + (parseFloat(item.amount) || 0);
    }, 0);
    form.afterDiscount_amount = (total1).toFixed(2)
}
//计算总税额
const calculateTotalTax = () => {
    const total = form.detailList.reduce((sum, item) => {
        return sum + (parseFloat(item.tax_amount) || 0);
    }, 0);
    form.tax_amount = total.toFixed(2);
}
//计算订单总数量
const calculateTotalNum = () => {
    const total = form.detailList.reduce((sum, item) => {
        return sum + (parseFloat(item.procureDetails_num) || 0);
    }, 0);
    form.procurementOrder_num = Number(total.toFixed(0));
}

//选择添加的商品
const openGoodsDialogView = ref(false)

const openGoodsDialog = () => {
    openGoodsDialogView.value = true;
}

// 处理选中的商品
const handleGoodsConfirm = (selectedGoods) => {
    console.log('选中的商品:', selectedGoods)

    if (selectedGoods && selectedGoods.length > 0) {
        // 转换商品数据格式，适配采购订单表格
        const newItems = selectedGoods.map(goods => ({
            goods_id: goods.id,
            goods_code: goods.code,
            goods_name: goods.name,
            goods_specifiction: goods.specification,
            goods_brand: goods.brandName,
            goods_price: 0, // 初始价格为0，需要手动填写
            procureDetails_num: 1,
            unitsId: goods.unit,
            goods_moreUint: goods.unitName,
            unitList: goods.unitList,
            goods_store: goods.warehouseName,
            store_userNum: goods.stock,
            goods_unit: goods.unitName,
            unit_num: '',
            procurementDetails_Deliverydate: '',
            gift: false,
            afterDiscount_price: 0,
            taxPrice: 0,
            afterDiscount_taxPrice: 0,
            discount: 0,
            discount_price: 0,
            discount_amount: 0,
            amount: 0,
            tax: 0,
            tax_amount: 0,
            totalAmount_includingTax: 0,
            companyCode: 'CNY001',
        }))


        // 添加到采购订单物品列表
        form.detailList.push(...newItems);
        console.log('newItem', form.detailList.values)
        updateUnitNum(...newItems)
        calculateTotalAmount();
        ElMessage.success(`成功添加 ${newItems.length} 个商品`);
    }
}

// 删除物品
const removeItem = (index) => {
    form.detailList.splice(index, 1);
    calculateTotalAmount();
    ElMessage.success('删除成功');
}

// 保存并且新增
const handleSubmit = async () => {
    if (isEdit.value) {
        await handleModify()
    } else {
        await handleAdd(true)
    }
}

// 保存
const handleSubmit2 = async () => {
    if (isEdit.value) {
        await handleModify()
    } else {
        await handleAdd(false)
    }
}
// 新增采购订单-手动添加
const handleAdd = async (isAddNew) => {
    // 验证供应商
    if (!selectedSupplier.SupplierName) {
        ElMessage.warning('请选择供应商');
        return;
    }

    // 验证物品信息
    if (form.detailList.length === 0) {
        ElMessage.warning('请至少添加一个采购物品');
        return;
    }

    try {
        await ElMessageBox.confirm('确定要提交采购订单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const orderData = {
            procurementOrder_code: form.procurementOrder_code,
            procurementOrder_date: formatDate(form.procurementOrder_date),
            supplier_code: form.supplier_code,
            supplier_name: form.supplier_name,
            procurement_code: form.procurement_code,
            comparison_code: form.comparison_code,
            procurement_amount: form.procurement_amount,
            discount_amount: form.discount_amount,
            afterDiscount_amount: form.afterDiscount_amount,
            tax_amount: form.tax_amount,
            procurementOrder_num: form.procurementOrder_num,
            procurementOrder_status: form.procurementOrder_status,
            created_by: form.created_by,
            staff_id: form.created_by,
            delivery_method: form.delivery_method,
            companyCode: form.companyCode,
            delivery_date: formatDate(form.delivery_date),
            procurementOrder_remark: form.procurementOrder_remark,
            isDelete: form.isDelete,
            detailList: form.detailList,
            supplier_shippingAddress: form.supplier_shippingAddress
        };

        const res = await axios.post('/lxw/insertProcurementOrder', orderData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });

        console.log(res)
        if (res.data.code == 5200) {
            ElMessage.success('订单提交成功！');
            if (isAddNew) {
                handleReset();
            }
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.log('用户取消提交');
    }
}

//新增采购订单-选择源单
const openComparisonGoodsDialogView = ref(false)

const comparisonGoodsList = ref([])

const comparisonGoodsLoading = ref(false)
// 添加必要的响应式数据
const goodsSearch = ref('')
const selectedComparisonGoods = ref([])

// 处理表格选择变化
const handleComparisonSelectionChange = (selection) => {
    selectedComparisonGoods.value = selection
}

// 搜索商品
const searchGoods = () => {
    getComparisonGoods()
}

//比价单商品选择分页信息
const comparisonGoodsPageInfo = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
//分页变化
const changePage = (page) => {
    comparisonGoodsPageInfo.pageNum = page;
    getComparisonGoods()
};
// 获取源商品数据 - 修正参数传递
const getComparisonGoods = async () => {
    comparisonGoodsLoading.value = true
    try {
        const res = await axios.get('/lxw/selectComparisonByCondition', {
            params: {
                pageNum: comparisonGoodsPageInfo.pageNum,
                pageSize: comparisonGoodsPageInfo.pageSize,
                supplier_code: form.supplier_code,
                goods_name: goodsSearch.value,
                companyCode: 'CNY001'
            }
        })
        console.log("该供应商下的比价商品信息", res)
        if (res.data.code == 5200) {
            comparisonGoodsList.value = res.data.comparisonDetails.list || []
            comparisonGoodsPageInfo.pageNum = res.data.comparisonDetails.pageNum
            comparisonGoodsPageInfo.pageSize = res.data.comparisonDetails.pageSize
            comparisonGoodsPageInfo.total = res.data.comparisonDetails.total
        } else {
            ElMessage.error(res.data.msg)
            comparisonGoodsList.value = []
        }
    } catch (error) {
        console.error('获取比价商品失败:', error)
        ElMessage.error('获取商品信息失败')
        comparisonGoodsList.value = []
    } finally {
        comparisonGoodsLoading.value = false
    }
}

// 确认选择比价商品
const confirmComparisonGoods = () => {
    if (selectedComparisonGoods.value.length === 0) {
        ElMessage.warning('请至少选择一件商品')
        return
    }

    // 转换比价商品数据为采购订单明细格式
    const newItems = selectedComparisonGoods.value.map(goods => ({
        goods_id: goods.goods_id,
        goods_code: goods.goods_code,
        goods_name: goods.goods_name,
        goods_specifiction: goods.goods_specifiction,
        goods_brand: goods.goods_brand,
        goods_unit: goods.goods_unit,
        goods_price: goods.supply_price || 0, // 使用报价单价
        procureDetails_num: 1, // 默认数量为1
        goods_moreUint: goods.goods_moreUint,
        goods_store: goods.goods_store, // 需要手动选择仓库
        store_userNum: goods.store_userNum, // 可用库存，需要从接口获取或设为0
        unit_num: 1, // 基本数量
        procurementDetails_Deliverydate: '', // 使用整单交货日期
        gift: false,
        afterDiscount_price: 0,
        taxPrice: 0,
        afterDiscount_taxPrice: 0,
        discount: 0,
        discount_price: 0,
        discount_amount: 0,
        amount: 0,
        tax: goods.supply_tax || 0, // 使用报价税率
        tax_amount: 0,
        totalAmount_includingTax: 0,
        companyCode: 'CNY001',
        // 保留比价相关信息
        comparison_code: goods.comparison_code,
        supply_price: goods.supply_price,
        supply_tax: goods.supply_tax
    }))

    // 添加到采购订单物品列表
    form.detailList.push(...newItems)

    // 重新计算所有商品的价格
    form.detailList.forEach(item => {
        calculateDetailPrice(item)
    })
    let map = freeGoodsRef.value.unitOptionsMap; //获取到的所有商品的单位列表
    form.detailList.forEach(i => { //
        console.log("detailList[i]: ", i);
        i.unitList = map[i.goods_id];
        console.log("i.unitList: ", i.unitList);
        updateUnitNum(i)
    })

    // 更新总计
    calculateTotalAmount()
    calculateTotalDiscountAmount()
    calculateTotal()
    calculateTotalTax()
    calculateTotalNum()

    ElMessage.success(`成功添加 ${newItems.length} 个商品`)
    openComparisonGoodsDialogView.value = false
    selectedComparisonGoods.value = [] // 清空选择
}

// 修改 chooseOrder 方法，添加验证
const chooseOrder = () => {
    if (!form.supplier_name) {
        ElMessage.warning("请先选择供应商")
        return
    }
    openComparisonGoodsDialogView.value = true
    goodsSearch.value = '' // 清空搜索条件
    selectedComparisonGoods.value = [] // 清空选择
    getComparisonGoods()
}
// 修改询价单
const handleModify = async () => {
    // 验证供应商
    if (!selectedSupplier.SupplierName) {
        ElMessage.warning('请选择供应商');
        return;
    }

    // 验证物品信息
    if (form.detailList.length === 0) {
        ElMessage.warning('请至少添加一个采购物品');
        return;
    }

    try {
        await ElMessageBox.confirm('确定要修改采购订单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const orderData = {
            procurementOrder_id: form.procurementOrder_id,
            procurementOrder_code: form.procurementOrder_code,
            procurementOrder_date: formatDate(form.procurementOrder_date),
            supplier_code: form.supplier_code,
            supplier_name: form.supplier_name,
            procurement_code: form.procurement_code,
            comparison_code: form.comparison_code,
            procurement_amount: form.procurement_amount,
            discount_amount: form.discount_amount,
            afterDiscount_amount: form.afterDiscount_amount,
            tax_amount: form.tax_amount,
            procurementOrder_num: form.procurementOrder_num,
            procurementOrder_status: form.procurementOrder_status,
            created_by: form.created_by,
            delivery_method: form.delivery_method,
            companyCode: form.companyCode,
            delivery_date: formatDate(form.delivery_date),
            procurementOrder_remark: form.procurementOrder_remark,
            isDelete: form.isDelete,
            detailList: form.detailList,
            supplier_shippingAddress: form.supplier_shippingAddress
        };

        const res = await axios.post('/lxw/updateProcurementOrder', orderData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });

        console.log(res)
        if (res.data.code == 5200) {
            ElMessage.success('订单修改成功！');
            router.back();
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.log('用户取消修改');
    }
}

// 日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};
// 重置表单
const handleReset = () => {
    Object.assign(selectedSupplier, {
        SupplierName: '',
        SupplierConcat: '',
        SupplierPhone: '',
        supplierAddress: '',
        totalDebt: 0
    });
    Object.assign(form, {
        procurementOrder_id: '',
        procurementOrder_code: '',
        procurement_code: '',
        salesSlip_code: '',
        comparison_code: '',
        procurement_amount: '',
        discount_amount: '',
        afterDiscount_amount: '',
        tax_amount: '',
        procurementOrder_num: '',
        procurementOrder_status: 1,
        created_by: '',
        delivery_method: '',
        companyCode: 'CNY001',
        procurementOrder_date: new Date(),
        delivery_date: '',
        supplier_code: '',
        supplier_name: '',
        procurementOrder_remark: '',
        isDelete: 0,
        supplier_shippingAddress: selectedSupplier.supplierAddress || '',
        detailList: []
    });
    fileList.value = [];
    ElMessage.info('表单已重置');
}


// 处理供应商选择确认
const handleSupplierConfirm = (supplier) => {
    if (supplier) {
        Object.assign(selectedSupplier, supplier);
        ElMessage.success(`已选择供应商：${supplier.SupplierName || '空选'}`);
    } else {
        // 如果 supplier 是 null 或 undefined，清空 selectedSupplier
        Object.keys(selectedSupplier).forEach(key => {
            selectedSupplier[key] = '';
        });
        ElMessage.success('已选择空选');
    }
    form.supplier_code = supplier?.SupplierCode || ''
    form.supplier_name = supplier?.SupplierName || ''
    form.supplier_shippingAddress = supplier?.supplierAddress || ''
};
// 合计行方法
const getSummary = (param) => {
    const { columns, data } = param
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计'
            return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(val => !isNaN(val))) {
            sums[index] = ''
            return
        }
        const total = values.reduce((prev, curr) => prev + curr, 0)
        sums[index] = total.toFixed(2)
    })
    return sums
}
</script>

<style scoped>
/* Loading 样式 */
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.loading-content {
    text-align: center;
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.loading-text {
    margin-top: 16px;
    color: #606266;
    font-size: 14px;
}

/* 隐藏对话框的样式 */
:deep(.hidden-dialog) {
    display: none !important;
}

:deep(.hidden-dialog .el-overlay) {
    display: none !important;
}

:deep(.hidden-dialog .el-dialog) {
    display: none !important;
}


.purchase-apply-container {
    height: 100%;
}

.form-card {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}

.order-number {
    font-size: 14px;
    color: #606266;
}

.fixed-height-dialog {
    max-height: 80vh;
}

:deep(.fixed-height-dialog .el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;
}

/* 供应商头部信息 */
.supplier-header {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    background-color: #fafafa;
}

.supplier-info-row,
.supplier-detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.supplier-detail-row {
    margin-bottom: 0;
}

.info-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 14px;
    color: #606266;
    margin-right: 8px;
    min-width: 80px;
}

.label.warning {
    color: #e6a23c;
}

.value {
    font-size: 14px;
    color: #303133;
}

.value.warning {
    color: #e6a23c;
    font-weight: bold;
}

/* 表单内容区域 - 可滚动 */
.form-content {
    flex: 1;
    overflow-y: auto;
    padding: 0 20px;
    max-height: calc(100vh - 300px);
}

/* 固定底部操作按钮 */
.form-footer {
    border-top: 1px solid #e8e8e8;
    padding: 16px 20px;
    background: #fff;
    position: sticky;
    bottom: 0;
    z-index: 10;
}

.form-actions {
    text-align: center;
}

/* 采购明细区域 */
.form-section {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    display: flex;
    align-items: center;
}

.section-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}

.operator-info {
    font-size: 14px;
    color: #606266;
}

.item-count {
    margin-left: auto;
    font-size: 14px;
    color: #606266;
    margin-left: 10px;
}

.items-table {
    margin-bottom: 16px;
}

/* 总计区域 */
.total-summary {
    margin-top: 16px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e8e8e8;
}

.summary-row {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 40px;
}

.summary-item {
    display: flex;
    align-items: center;
}

.summary-label {
    font-size: 14px;
    color: #606266;
    margin-right: 8px;
}

.summary-value {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
}

.summary-value.total-amount {
    font-size: 18px;
    color: #f56c6c;
}

/* 优化表格样式 */
:deep(.items-table .el-table__empty-block) {
    min-height: 100px;
}

:deep(.items-table .el-table__empty-text) {
    color: #909399;
    font-size: 14px;
}

:deep(.el-upload__tip) {
    font-size: 12px;
    color: #909399;
    margin-top: 7px;
}

/* 源单选择对话框样式 */
.supplier-dialog-content {
    padding: 0 20px;
}

.search-area {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.dialog-footer {
    margin-top: 20px;
    text-align: right;
}

/* 表格样式优化 */
:deep(.supplier-table .el-table__header-wrapper) {
    background-color: #f5f7fa;
}

:deep(.supplier-table .el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
}
</style>